package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.dto.request.LoginRequest;
import com.example.domain.dto.request.RegisterRequest;
import com.example.domain.entity.Person;
import com.example.domain.query.PersonQuery;
import com.example.mapper.PersonMapper;
import com.example.service.IPersonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-05-12
 */
@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, Person> implements IPersonService {
    @Autowired
    private PersonMapper personMapper;

    @Override
    public Person register(RegisterRequest request) {
        // 验证手机号是否已被注册
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", request.getPhone());
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("该手机号已被注册");
        }

        // 创建新用户
        Person person = new Person();
        person.setPersonName(request.getPersonName());
        person.setPhone(request.getPhone());
        person.setPassword(request.getPassword());
        person.setTitle(request.getTitle());

        // 保存用户信息
        this.save(person);
        return person;
    }

    @Override
    public Person login(LoginRequest request) {
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        // 支持工号或手机号登录
        try {
            // 尝试将标识符解析为工号（整数）
            int personId = Integer.parseInt(request.getIdentifier());
            queryWrapper.eq("person_id", personId);
            queryWrapper.or().eq("phone", request.getIdentifier());
        } catch (NumberFormatException e) {
            // 如果解析失败，则视为手机号登录
            queryWrapper.eq("phone", request.getIdentifier());
        }

        Person person = this.getOne(queryWrapper);
        if (person == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!person.getPassword().equals(request.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return person;
    }

    @Override
    public IPage<Person> pageQuery(PersonQuery query, int pageNum, int pageSize) {
        Page<Person> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Person> wrapper = new QueryWrapper<>();

        if (query != null) {
            if (query.getPersonId() != null) {
                wrapper.eq("person_id", query.getPersonId());
            }
            if (StringUtils.hasText(query.getPersonName())) {
                wrapper.like("person_name", query.getPersonName());
            }
            if (query.getDeptId() != null) {
                wrapper.eq("dept_id", query.getDeptId());
            }
            if (query.getHireDate() != null) {
                wrapper.apply("DATE(hire_date) = DATE({0})", query.getHireDate());
            }
            if (StringUtils.hasText(query.getEducation())) {
                wrapper.like("education", query.getEducation());
            }
            if (StringUtils.hasText(query.getMajor())) {
                wrapper.like("major", query.getMajor());
            }
            if (StringUtils.hasText(query.getTitle())) {
                wrapper.like("title", query.getTitle());
            }
            if (StringUtils.hasText(query.getPhone())) {
                wrapper.like("phone", query.getPhone());
            }
            if (StringUtils.hasText(query.getAddress())) {
                wrapper.like("address", query.getAddress());
            }
            if (StringUtils.hasText(query.getProfile())) {
                wrapper.like("profile", query.getProfile());
            }
        }
        return this.page(page, wrapper);
    }

    public boolean schedule(Integer personId, Integer deptId) {
        UpdateWrapper<Person> wrapper = new UpdateWrapper<>();
        wrapper.eq("person_id", personId)
                .set("dept_id", deptId);
        this.personMapper.update(wrapper);
        return true;
    }

    public Person getByPhone(String phone) {
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        List<Person> personList = this.personMapper.selectList(queryWrapper);
        if(personList.isEmpty()) {
            return null;
        }
        return personList.get(0);
    }

    @Override
    public boolean updatePassword(String phone, String newPassword) {
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        Person person = this.getOne(queryWrapper);

        if (person == null) {
            return false; // 用户不存在
        }

        person.setPassword(newPassword);
        return this.updateById(person);
    }
}
